<?php
declare (strict_types = 1);
/**
 * Created by PhpStorm.
 * User: broceli
 * Date: 19-9-9
 * Time: 下午4:37
 */

namespace App\Tool;

use App\Lib\Jwt\Jwt;

class Tool
{

    /**
     * 加密数组
     * @param String $str
     * @return string
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     */
    public static function serializeArr(String $str)
    {
        // 自定义的加解密的key
        $key = \config('saas.token.key');
        // 自定义的16位的iv
        $iv = \config('saas.token.iv');

        $opensslEncryptType = \config('saas.token.openssl_encrypt_type');
        return base64_encode(openssl_encrypt($str, $opensslEncryptType, $key, 0, $iv));
    }

    /**
     * 配合serializeArr方法实现加密解密 也可以降低传入参数的长度
     * @param String $str
     * @return Array
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     */
    public static function unSerializeArr(String $str): Array
    {
        // 自定义的加解密的key
        $key = \config('saas.token.key');
        // 自定义的16位的iv
        $iv = \config('saas.token.iv');

        $opensslEncryptType = \config('saas.token.openssl_encrypt_type');
        return openssl_decrypt($str, $opensslEncryptType, $key, 0, $iv);
    }

    public function uniqid($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }
}